package com.zsx.shopping.search.controller;

import com.zsx.shopping.common.api.R;
import com.zsx.shopping.common.exception.InvalidParamException;
import com.zsx.shopping.search.param.SearchParam;
import com.zsx.shopping.search.service.SearchService;
import com.zsx.shopping.search.vo.SearchResultVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/search/search")
public class SearchController {

    @Resource
    private SearchService searchService;

    @GetMapping("/product")
    public R<SearchResultVo> searchProduct(SearchParam searchParam) {
        validCheck(searchParam);
        SearchResultVo searchResultVo = searchService.searchProduct(searchParam);
        return R.success(searchResultVo);
    }

    private void validCheck(SearchParam searchParam) {
        String sort = searchParam.getSort();
        if (!StringUtils.isEmpty(sort)) {
            String[] s = sort.split("_");
            if (s.length < 2) {
                throw new InvalidParamException();
            }
        }
        String skuPrice = searchParam.getSkuPrice();
        if (!StringUtils.isEmpty(skuPrice)) {
            String[] s = skuPrice.split("_");
            if (!StringUtils.isNumeric(s[0])) {
                throw new InvalidParamException();
            }
            if (s.length >= 2 && !StringUtils.isNumeric(s[1])) {
                throw new InvalidParamException();
            }
        }
        List<String> attrs = searchParam.getAttrs();
        if (attrs != null) {
            for (String attr : attrs) {
                if (!StringUtils.isEmpty(attr)) {
                    String[] s = attr.split("_");
                    if (s.length < 2 || !StringUtils.isNumeric(s[0])) {
                        throw new InvalidParamException();
                    }
                }
            }
        }
    }
}
